var sock,
//	storage = window.sessionStorage,
	storage = window.localStorage,
	historyMsg = JSON.parse(storage.history || '[]'),
	content = $('#msgContent'),
	msg = $('#msg'),
	reconnect=1,
	identiconOpt={background:[255,255,255,255],margin:.1,size:100},
	tmpl = laytpl($('#tmpl').html()),
	msgscroll,
	player = new Audio();
$(function() {
	if ('WebSocket' in window) {
		//初始化滚动条
		msgscroll = new IScroll('#iscroll');
		//点击消息体滚屏到最底部，采用防抖处理
		$('#iscroll').on('tap',debounce(function(){
			$('#iscroll').height($('body').height()-$('#operate').height());
			var top = -content.height()+$('#iscroll').height();
			if(top<0){
				msgscroll.refresh();
				msgscroll.scrollTo(0,top,500, IScroll.utils.ease.circular);
			}
		},500))
		// 初始化历史消息
		$.each(historyMsg, function(i, data) {
			tmpl.render(data, function(html){content.append(html)})
		})
		//初始化历史消息后要刷新滚动条
		$(window).on('resize',function(){$('#iscroll').trigger('tap')}).trigger('resize');
		$('#name').val(storage.name || '');//初始化登录窗
		$('#joinbtn').on('click', initSocket)
		//回车键发送消息，删除键碰到表情删除整个表情
		msg.on('keydown', function(e) {
			var code = e.keyCode;
			if(code == 13){
				sendMsg();
			}else if (code == 8 && /\[#\d+\]$/.test(msg.val())) {
				msg.val(msg.val().replace(/\[#\d+\]$/, ''))
				return false;
			}
		}).on('focus', function(){
			content.trigger('tap');
		})
		//点击消息时自动收起表情选择和插件选择相关的界面并滚屏到最底部
		content.on('tap',function(e) {
			if($('#facebox').hasClass('show')){
				closeFace();
			}else if($('#pluginbox').hasClass('show')){
				closePlugin();
			}
		})
		// 初始化表情相关
		initFace();
		//初始化插件相关的事件
		initPlugin();
	} else {
		$('body').html('您的浏览器不支持HTML5 WebSocket').css({
			fontSize : '3rem',
			textAlign : 'center'
		});
	}
})
function initSocket() {
	var name = $('#name').blur();
	if (name.val().trim()) {
		sock = new WebSocket('ws://' + location.host + '/webchat');
		sock.onopen = function() {
			storage.name = name.val().trim();
			sock.send(JSON.stringify({action : 'login',usr : storage.name}));
		}
		sock.onmessage = function(e) {
			var data = JSON.parse(e.data);
			if (data.type != 'login') {
				tmpl.render(data,function(html) {
					var items = content.append(html).find('.item');
					items.length > 50&&items.slice(0,items.length-50).remove();
					$('#iscroll').trigger('tap');
					data.type!='notify'&&historyMsg.push(data);
					if (historyMsg.length > 50)
						historyMsg = historyMsg.slice(historyMsg.length-50,historyMsg.length)
					storage.history = JSON.stringify(historyMsg);
				})
				if(navigator.vibrate&&data.uid != storage.uid)navigator.vibrate(500)
			} else {
				$('#login').addClass('hide');
				$('#content').removeClass('blur')
				storage.uid = data.uid;
			}
		}
		sock.onclose = function(){
			reconnect&&initSocket();
		};
		sock.onerror = function() {
			reconnect = confirm('连接服务器失败，是否重连？');
		}
	} else {
		alert('请输入昵称~');
	}
}
function sendMsg() {
	if (msg.val().trim()) {
		sock.send(JSON.stringify({
			action : 'talk',
			usr : storage.name,
			msg : msg.val().trim()
		}))
		msg.val('');
	}
}
//表情相关
function initFace(){
	$('#addface').on('click', toggleFace);
	$('#facebox').on('click', '.face', function() {
		var _this = $(this);
		if (!_this.hasClass('iconfont')) {
			msg.val(msg.val() + '[#' + _this.data('i') + ']');
		} else {
			closeFace();
			sendMsg();
		}
	}).on('click','.dot',function(){
		var _this = $(this);
		if(!_this.hasClass('current')){
			showFace($(this).index()+1);
		}
	}).on('swipeLeft', function() {
		var next =$('.dot.current').index()+2;
		showFace(next<6?next:1);
	}).on('swipeRight', function() {
		var next =$('.dot.current').index();
		showFace(next?next:5);
	})
}
function showFace(nextPage) {
	$('#pluginbox').removeClass('show');
	laytpl($('#tmpl-face').html()).render(nextPage||1, function(html) {
		$('#facebox').html(html).addClass('show');
		$('#iscroll').trigger('tap');
	})
}
function closeFace() {
	$('#facebox').removeClass('show').empty();
	$('#iscroll').trigger('tap');
}
function toggleFace(){
	$('#facebox').hasClass('show')?closeFace():showFace();
}
function initPlugin(){
	$('#pluginbtn').on('click', togglePlugin);
	// 发送图片
	$('#addimg').on('change', 'input', function() {
		var _this = $(this);
		var reader = new FileReader();
		reader.onload = function(f) {
			compressImg(this.result, function(data) {
				closePlugin();
				sock.send(JSON.stringify({
					action : 'img',
					usr : storage.name,
					msg : data.split(',')[1]
				}));
			});
		};
		reader.readAsDataURL(this.files[0]);
		_this.clone().insertAfter(_this);
		_this.remove();
	})
	//音乐相关
	var mp3box = $('#musicbox').on('click','.s-m-item',function(){
		var _this = $(this);
		sock.send(JSON.stringify({action:'music',usr:storage.name,url:_this.data('src') ,msg:_this.text()}));
		mp3box.trigger('swipeRight');
	}).on('swipeRight',function(){
		$(this).removeClass('show').find('.s-m-item').remove();
		$('#musicname').val('');
		closePlugin();
	})
	$('#close-musicbox-btn').on('click',function(){
		mp3box.trigger('swipeRight');
	})
	$('#musicbtn').on('click',function(){
		mp3box.addClass('show')
	})
	$('#musicname').on('input',debounce(function(){
		var name = $(this).val().trim();
		if(name){
			$.post('/music',{name:name},function(list){
				var html = '';
				$.each(list,function(i,n){
					html+='<div class="s-m-item" data-src="'+n.url+'">'+n.name+' - '+n.art+'</div>';
				})
				$('.s-m-item').remove();
				$('#musicbox').append(html);
			},'json')
		}else{
			$('.s-m-item').remove();
		}
	},700))
	content.on('tap','.music',function(){
		msgscroll.scrollToElement(this,500,0,0, IScroll.utils.ease.circular);
		var _this = $(this);
		if(_this.hasClass('play')){
			_this.removeClass('play');
			player.pause();
		}else{
			$('.play').removeClass('play');
			_this.addClass('play');
			player.src = _this.data('music');
			player.play();
		}
		return false;
	})
	$(player).on('ended',function(){
		$('.play').removeClass('play');
	})
	//发送地理位置
	$('#location').on('click',function(){
		if (navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position) {
				closePlugin();
				sock.send(JSON.stringify({action : 'location',usr : storage.name,location:position.coords.longitude+','+position.coords.latitude}));
			}, function(err) {
				alert('获取定位失败');
			},{
				enableHighAccuracy: true,
				timeout: 3000,
				maximumAge: 60
			});
		}else{
			alert('您的设备不支持定位');
		}
	})
}
function showPlugin(){
	$('#pluginbox').addClass('show');
	$('#facebox').removeClass('show').empty();
	$('#iscroll').trigger('tap');
}
function closePlugin(){
	$('#pluginbox').removeClass('show');
	$('#iscroll').trigger('tap');
}
function togglePlugin(){
	$('#pluginbox').hasClass('show')?closePlugin():showPlugin();
}